package open.panxiong.shared.http.model

import com.google.gson.Gson
import fi.iki.elonen.NanoHTTPD.Response
import fi.iki.elonen.NanoHTTPD.newFixedLengthResponse

const val mime_type_text = "text/plain"
const val mime_type_json = "application/json"

const val TEXT_404 = "404 NOT FOUND"

data class NanohttpdResponse(
    var code: Int = 0,
    var msg: String = "OK",
    var data: Any? = null
) {

    fun toJson(): Response {
        val data = Gson().toJson(this)
        return newFixedLengthResponse(Response.Status.OK, mime_type_json, data)
    }

    fun toText(): Response {
        return newFixedLengthResponse(Response.Status.OK, mime_type_text, this.toString())
    }

    fun to404(): Response {
        return newFixedLengthResponse(Response.Status.NOT_FOUND, mime_type_text, TEXT_404)
    }

    fun to500(msg: String = "服务器内部错误"): Response {
        return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, mime_type_text, msg)
    }

}